package com.x.dao.student;

import com.x.bean.Achievement;
import com.x.bean.User;
import com.x.dao.BaseDao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 13925
 */
public class StudentDaoImpl implements StudentDao {


    @Override
    public int updateStudent(Connection connection, User user) throws SQLException {
        PreparedStatement pstm = null;
        int updateRows = 0;
        if (connection != null) {
            String sql = "update user set name = ?, password = ? where code = ?";
            Object[] params = {user.getName(), user.getPassword(), user.getCode()};
            updateRows = BaseDao.executeUpdate(connection, pstm, sql, params);
            BaseDao.closeResource(null, pstm, null);
        }
        return updateRows;
    }

    @Override
    public List<Achievement> getAchievementByCode(Connection connection, String code) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet resultSet = null;
        ArrayList<Achievement> achievementsList = new ArrayList<>();
        if (connection != null) {
            String sql = "select a.*, u.name as name from user u, achievement a where a.code = u.code and a.code = ?";
            List<Object> list = new ArrayList<Object>();
            list.add(code);
            Object[] params = list.toArray();
            resultSet = BaseDao.excuteQuery(connection, pstm, resultSet, sql, params);

            while (resultSet.next()) {
                Achievement achievement = new Achievement();
                achievement.setAid(resultSet.getInt("Aid"));
                achievement.setCourseNo(resultSet.getString("courseNo"));
                achievement.setCourseName(resultSet.getString("courseName"));
                achievement.setScore(resultSet.getString("score"));
                achievement.setName(resultSet.getString("name"));
                achievement.setCode(resultSet.getString("code"));
                achievementsList.add(achievement);
            }
            BaseDao.closeResource(null, pstm, resultSet);
        }
        return achievementsList;
    }
}
